import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import 'rxjs/add/operator/switchMap';
import { appService } from '../../../../../my-service/app.service';

declare var $: any;
declare var io: any;
@Component({
  selector: 'blockcanvas-root',
  templateUrl: './blockcanvas.component.html',
  styleUrls: ['./blockcanvas.component.css']
})
export class blockcanvasComponent implements OnInit, OnDestroy {
  @Input() CanvasGroupGuid: any
  @Input() mainH: any
  @Input() mainW: any
  anchor = []
  addwindow = false
  load = false
  blockModel={
    AddCoordinates: {x: "", y: ""},
    AddRule: {x: '0', y:'0'},
    BackgroundColor: "",
    BlockHeight: 0,
    BlockWidth: 0,
    Color: "",
    Distance: 0,
    FK_CanvasGuid: "",
    ID: 0,
    InitialCoordinates: {x: "", y: ""},
    PK_BlockModelGuid: "",
    data: []
  }
  config = {
    HaveTitle: 0,
    HaveAuthor: 0,
    PK_AnchorGuid: '',
    PK_BlockGuid: ''
  }
  updata = false;
  selectBlockGuid='';
  canopenadd = false;//控制详情弹出框的
  private pointdata: any;
  constructor(
    private appservice: appService
  ) { }
  ngOnInit() {
    this.getData()
  }
  async getData() {
    this.load=false
    this.blockModel={
      AddCoordinates: {x: "", y: ""},
      AddRule: {x: '0', y:'0'},
      BackgroundColor: "",
      BlockHeight: 0,
      BlockWidth: 0,
      Color: "",
      Distance: 0,
      FK_CanvasGuid: "",
      ID: 0,
      InitialCoordinates: {x: "", y: ""},
      PK_BlockModelGuid: "",
      data: []
    }
    //获取块模板
    let blockModel = await this.appservice.blockModel(this.CanvasGroupGuid).then(re => re[0])
    //检查,如果该画布是第一次
    let data = {
      FK_CanvasGroupGuid: this.CanvasGroupGuid,
      FK_BlockModelGuid: blockModel.PK_BlockModelGuid
    }
    await this.appservice.check(data).then(res => res)
    //获取块并统一处理所有数据，将锚点和标签加到块上
    await this.appservice.block(this.CanvasGroupGuid).then(re => {
      //遍历块模板
        blockModel.AddCoordinates = JSON.parse(blockModel.AddCoordinates)
        blockModel.InitialCoordinates = JSON.parse(blockModel.InitialCoordinates)
        blockModel.AddRule = JSON.parse(blockModel.AddRule)
        blockModel.data = []
        //遍历所有的块
        for(let i=0;i<re.length;i++){
          if (re[i].FK_BlockModelGuid == blockModel.PK_BlockModelGuid) {
            re[i].Coordinates = JSON.parse(re[i].Coordinates)
            re[i].Anchor = []
            blockModel.data.push(re[i])
          }
        }
      this.blockModel = blockModel
    })
    await this.getAnchor()
    await this.getNote()
    console.log(this.blockModel)
    this.load = true
  }
  async getAnchor() {
    //获取块模板下的锚点
    this.anchor = await this.appservice.getPointer(this.CanvasGroupGuid).then(re => {
      for(let i=0;i<re.length;i++){
        re[i].Coordinate = JSON.parse(re[i].Coordinate)
        re[i].AddCoordinate = JSON.parse(re[i].AddCoordinate)
      }
      for(let i=0;i<this.blockModel.data.length;i++){
        for(let j=0;j<re.length;j++){
          for (let m = 0; m < re[j].Coordinate.length; m++) {
            re[j].Coordinate[m].note = []
          }
          re[j].note = []
          if ( re[j].FK_BlockModelGuid == this.blockModel.PK_BlockModelGuid) {
            this.blockModel.data[i].Anchor.push({
              AddCoordinate:  re[j].AddCoordinate,
              AddSmColor:  re[j].AddSmColor,
              AddColor:  re[j].AddColor,
              AnchorName:  re[j].AnchorName,
              Color:  re[j].Color,
              Coordinate:  re[j].Coordinate,
              FontColor:  re[j].FontColor,
              NoteHeight:  re[j].NoteHeight,
              NoteWidth:  re[j].NoteWidth,
              PK_AnchorGuid:  re[j].PK_AnchorGuid,
              note:  re[j].note
            })
          }

        }
      }
      return re
    })
  }
  async getNote() {

      await this.appservice.getallnote(this.CanvasGroupGuid).then(re => {
      for(let k=0;k<re.length;k++){
        for(let i=0;i<this.blockModel.data.length;i++){
          for(let j=0;j<this.blockModel.data[i].Anchor.length;j++){
              // console.log(this.blockModel.data[i].PK_BlockGuid)
              // console.log(this.blockModel.data[i].Anchor[j].PK_AnchorGuid)
              if (re[k].FK_BlockGuid == this.blockModel.data[i].PK_BlockGuid && re[k].FK_AnchorGuid == this.blockModel.data[i].Anchor[j].PK_AnchorGuid) {
                this.blockModel.data[i].Anchor[j].Coordinate[0].note.push(re[k])
                        // item2.note.push(item4)
                        this.blockModel.data[i].Anchor[j].note.push(re[k])
              }
            }
          }
        }
     })
      // for (let item1 of this.blockModel.data) {
      //   for (let item2 of item1.Anchor) {
      //     for (let item4 of this.allNote) {
      //       if (item4.FK_BlockGuid == item1.PK_BlockGuid && item4.FK_AnchorGuid == item2.PK_AnchorGuid) {
      //         item2.Coordinate[0].note.push(item4)
      //         // item2.note.push(item4)
      //         item2.note.push(item4)
      //         // let min = item2.Coordinate[0].note;
      //         // for (let i = 0; i < item2.Coordinate.length; i++) {
      //         //   if (item2.Coordinate[i].note.length < min.length) {
      //         //     min = item2.Coordinate[i].note;
      //         //   }
      //         // }
      //         // min.push(item4);
      //       }
      //     }
      //   }
      // }

  }
  del($event){
    this.updata = true;
    this.appservice.delnote($event).then(re => {
      if (re.PK_NoteGuid) {
        for(let j=0;j<this.blockModel.data.length;j++){
          for(let k =0;k<this.blockModel.data[j].Anchor.length;k++){
            for(let m=0;m<this.blockModel.data[j].Anchor[k].note.length;m++){
              if (re.PK_NoteGuid == this.blockModel.data[j].Anchor[k].note[m].PK_NoteGuid) {
                this.blockModel.data[j].Anchor[k].note.splice(m,1)
              }
            }
            for(let w=0;w<this.blockModel.data[j].Anchor[k].Coordinate.length;w++){
              for(let q=0;q<this.blockModel.data[j].Anchor[k].Coordinate[w].note.length;q++){
                if (re.PK_NoteGuid == this.blockModel.data[j].Anchor[k].Coordinate[w].note[q].PK_NoteGuid) {
                  this.blockModel.data[j].Anchor[k].Coordinate[w].note.splice(q,1)
                }
              }
            }
          }
        }
    }
   })
  }
  recovery(PK_NoteGuid){
    this.getOneNote(PK_NoteGuid)
  }
  getOneNote(PK_NoteGuid){
    this.appservice.getonenote(PK_NoteGuid).then((re) => {
        for(let j=0;j<this.blockModel.data.length;j++){
          for(let k =0;k<this.blockModel.data[j].Anchor.length;k++){
              if (re.FK_AnchorGuid == this.blockModel.data[j].Anchor[k].PK_AnchorGuid&&re.FK_BlockGuid==this.blockModel.data[j].PK_BlockGuid) {
                this.blockModel.data[j].Anchor[k].note.push(re)
                let min = this.blockModel.data[j].Anchor[k].Coordinate[0].note;
                for (let i = 0; i < this.blockModel.data[j].Anchor[k].Coordinate.length; i++) {
                  if (this.blockModel.data[j].Anchor[k].Coordinate[i].note.length < min.length) {
                    min = this.blockModel.data[j].Anchor[k].Coordinate[i].note;
                  }
                }
                min.push(re);
              }
          }
        }
    })
  }
  openAdd(anchor,block) {
    if (anchor.note.length > 0) {
      this.pointdata = anchor;
      this.selectBlockGuid = block.PK_BlockGuid
      this.canopenadd = true;
    }
    else { return }
  }
  async addBlock(blockModel) {
    let limit = {
      direction: '',
      num: 0
    };
    if (blockModel.AddRule.x == "Infinite") {
      limit = {
        direction: 'y',
        num: blockModel.AddRule.y
      }
    } else {
      limit = {
        direction: 'x',
        num: blockModel.AddRule.x
      }
    }
    let blockLength = blockModel.data.length
    let column = 0
    let row = 0
    if (limit.direction == 'x') {
      column = (blockLength + 1) % limit.num == 0 ? limit.num : (blockLength + 1) % limit.num
      row = Math.ceil((blockLength + 1) / limit.num)
    }
    else {
      row = (blockLength + 1) % limit.num == 0 ? limit.num : (blockLength + 1) % limit.num
      column = Math.ceil((blockLength + 1) / limit.num)
    }

    let config = {
      row: row,
      column: column,
      distance: blockModel.Distance,
      blockWidth: blockModel.BlockWidth,
      blockHeight: blockModel.BlockHeight,
      InitialCoordinatesX: blockModel.InitialCoordinates.x,
      InitialCoordinatesY: blockModel.InitialCoordinates.y
    }
    let apiConfig = {
      FK_BlockModelGuid: blockModel.PK_BlockModelGuid,
      Coordinates: JSON.stringify(this.getCoordinate(config)),
      FK_CanvasGroupGuid: this.CanvasGroupGuid,
      IsInitial: 'false'
    }
    let addBlockRes = await this.appservice.addBlock(apiConfig).then(re => re)
    // await  this.getData()
    let newBlock={
      Coordinates: this.getCoordinate(config),
      FK_BlockModelGuid: blockModel.PK_BlockModelGuid,
      PK_BlockGuid: addBlockRes.guid,
      IsInitial: 'false',
      Anchor:[]
    }
    //给新的板块加上锚点
    for (let item3 of this.anchor) {
      for (let i = 0; i < item3.Coordinate.length; i++) {
        item3.Coordinate[i].note = []
      }
      item3.note = []
      if (item3.FK_BlockModelGuid == newBlock.FK_BlockModelGuid) {
        newBlock.Anchor.push({
          AddCoordinate: item3.AddCoordinate,
          AddSmColor: item3.AddSmColor,
          AddColor: item3.AddColor,
          AnchorName: item3.AnchorName,
          Color: item3.Color,
          Coordinate: item3.Coordinate,
          FontColor: item3.FontColor,
          NoteHeight: item3.NoteHeight,
          NoteWidth: item3.NoteWidth,
          PK_AnchorGuid: item3.PK_AnchorGuid,
          note: item3.note
        })
      }
    }
    blockModel.data.push(newBlock)
  }
  getCoordinate({ row, column, distance, blockWidth, blockHeight, InitialCoordinatesX, InitialCoordinatesY }) {
    let newCoordinates = { x: `${(column - 1) * (blockWidth + distance) + parseInt(InitialCoordinatesX)}%`, y: `${(row - 1) * (blockHeight + distance) + parseInt(InitialCoordinatesY)}%` }
    return newCoordinates
  }
  addNote(PK_AnchorGuid, PK_BlockGuid, HaveAuthor, HaveTitle) {
    this.addwindow = true;
    this.config = {
      HaveAuthor: HaveAuthor,
      HaveTitle: HaveTitle,
      PK_AnchorGuid: PK_AnchorGuid,
      PK_BlockGuid: PK_BlockGuid
    }
  }
  add($event) {
  this.updata = true;
  this.addwindow = true;
  this.config = {
    HaveAuthor: $event.HaveAuthor,
    HaveTitle: $event.HaveTitle,
    PK_AnchorGuid: $event.PK_AnchorGuid,
    PK_BlockGuid: this.selectBlockGuid
  }

   this.addNote(this.config.PK_AnchorGuid, this.config.PK_BlockGuid, this.config.HaveTitle, this.config.HaveAuthor)
  }
  noteHover(dom, data,PK_BlockGuid) {
    if(data.note.length>1){
      dom.style.display = 'flex'
    }
    // let list=[]
    // for(let item of data.note){
    //   if(item.FK_BlockGuid==PK_BlockGuid){
    //     list.push(item)
    //   }
    // }
    // if (list.length > 1) {
    //   dom.style.display = 'flex'
    // }
  }
  noteHoverEnd(dom) {
    dom.style.display = 'none'
  }
  async onok(data) {
    this.oncancel()
    data.PK_NoteGuid = this.appservice.GenGuid();
    data.FK_CanvasGroupGuid = this.CanvasGroupGuid;
    await this.appservice.postnote(data).then(re => re)
      for(let item2 of this.blockModel.data){
        for(let item3 of item2.Anchor){
          if(item3.PK_AnchorGuid==data.PK_AnchorGuid&&data.PK_BlockGuid==item2.PK_BlockGuid){
            let newNote={
              Content:data.Content,
              FK_AnchorGuid: data.PK_AnchorGuid,
              FK_BlockGuid: data.PK_BlockGuid,
              FK_CanvasGroupGuid: this.CanvasGroupGuid,
              Name: data.name,
              PK_NoteGuid: data.PK_NoteGuid,
              Score: 0,
              Title: data.Title
            }
            item3.note.push(newNote)
            let min = item3.Coordinate[0].note;
            for (let i = 0; i < item3.Coordinate.length; i++) {
              if (item3.Coordinate[i].note.length < min.length) {
                min = item3.Coordinate[i].note;
              }
            }
            min.push(newNote)
          }
        }
      }

  }
  closeAdd() {
    this.selectBlockGuid=''
    this.canopenadd = false
  }
  oncancel() {
    this.addwindow = false;
    this.config = {
      HaveTitle: 0,
      HaveAuthor: 0,
      PK_AnchorGuid: '',
      PK_BlockGuid: ''
    }
  }
  ngOnDestroy() {
  }
}
